﻿import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text } from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import Hearder from '../index/hearder'
import './pkgo.scss'

export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      result:[],
      qun_date:'',
      navindex:7,//用于判断导航选中
      pageheight:0,//获取高度
      qid:Taro.getStorageSync('dateinfo').qid,
      pageNumber:1,//页码数
      scrollPd:false,//是否可滑动
      hasNextPage:false,//是否有下一页
      znwns:'',
      nowDate:0,
      myTime: null
    }
  }
  config = {
    navigationBarTitleText: '加载中'
  }

  componentWillMount () {
    var _this=this
    Taro.getSystemInfo({
      success:function(res){
        _this.setState({
          pageheight: res.windowHeight
        })
      }   
    })
    _this.getquninfo()
    _this.getgoods(1)
  }

  componentWillUnmount () {
    clearTimeout(this.myTime)
  }

  getgoods(pageNumber){
    //获取商品列表
    // console.log(pageNumber+'pageNumber1')
    var _this=this;
    var date1={
      pageNumber:pageNumber,
      categoryId:0,
      clusterId:1941,
      auditType:2,
      online:1,
      status:1,
      commodityType:1,
      type:1,
      sortColumns:'sale_amount desc',
      pageSize:20
    }
    // console.log(JSON.stringify(date1)+'date1')
    CommonJs.ajaxRequest('/commodity/queryFreeGoPageDataAndOrder',date1,'GET',function(res){
      // console.log(JSON.stringify(res)+'//33333333333333333'+_this.state.qid)
        if (res) {
          var hasNextPage = res.hasNextPage
          var result = res.result
          var results = _this.state.result
          for(var i = 0; i < result.length; i++){
            results.push(result[i])
          }
          if (hasNextPage) {
            _this.setState({
              result:results,
              znwns: '暂无商品',
              pageNumber: res.pageNumber,
              hasNextPage: hasNextPage,
              scrollPd: true
            })
          } else {
            _this.setState({
              result:results,
              znwns: '暂无商品',
              pageNumber: res.pageNumber,
              hasNextPage: hasNextPage,
              scrollPd: false
            })
          }
          _this.countDown()
        } else {
          _this.setState({
            znwns: '暂无商品'
          })
        }
    })
    
  }
  loadMore(){
    var _this = this;
    var pd = _this.state.scrollPd;
    if(pd) {
      //防止多次触发滑动到底部事件
      _this.setState({
        scrollPd: false//禁止下拉
      })
      var pageNumber = _this.state.pageNumber + 1;
      _this.getgoods(pageNumber);
    }else{
      var hasNextPage =  _this.state.hasNextPage;
      if(hasNextPage){
        Taro.showToast({
            title:'正在加载数据...',
            icon: 'none',
            duration: 2000
          });
      }else{
        Taro.showToast({
            title:'没有更多数据啦！',
            icon: 'none',
            duration: 2000
          });
      }
    }
  }
  open(url,type){
    this.$preload({
      type:type
    })
    CommonJs.open(url);
  }
  opendetails(url,id,ids,did,sid,oid){
    // console.log(id+'id'+'ids'+ids)
    this.$preload({
      'commodityId':id,
      'shopId':ids,
      'dealerId':did,
      'shopCommodityId':sid,
      'freeGoOrderId':oid
    });
    CommonJs.openTo(url);
  }
  getquninfo(){
    var _this=this;
    var date1={id:_this.state.qid}
    CommonJs.ajaxRequest('/cluster/getEntityAndLoginId',date1,'GET',function(res){
      Taro.setNavigationBarTitle({title:res.content.name+"社群"})
        var query=Taro.createSelectorQuery()
        query.select('.qun-bgbanner').boundingClientRect(function(rect){
          var height=_this.state.pageheight
          _this.setState({
              qun_date: res.content,
              pageheight:height-rect.height
          })
        }).exec();
    })
    
  }
  onShareAppMessage(res){
    let title = '"'+this.state.qun_date.name+'社群"，点击进入，和我一起参加活动吧'
    let path = '/pages/activity/activity?scene='+this.state.qun_date.id
    let imageUrl = this.state.qun_date.photo
    return CommonJs.onShareAppMessage(title, path, imageUrl)
  }
  countDown(){
    //获取当前时间
    var _this = this
    var date = new Date()
    var nowDate = date.getTime()
    _this.setState({
      nowDate: nowDate
    })
    _this.myTime = setTimeout(() => { _this.countDown() }, 1000)
  }
  countDowns(dates, times){
    //倒计时处理
    var _this = this
    // console.log(JSON.stringify(dates)+'//////1111////'+JSON.stringify(times))
    if (dates >= times) {
      // console.log(JSON.stringify(dates)+'//////2222////'+JSON.stringify(times))
      
      // clearTimeout(_this.myTime)
      // _this.getgoods(1)
    } else {
      return CommonJs.countDowns(dates, times)
    }
  }
  render () {
    const result = this.state.result
    const list_date = this.state.qun_date
    // console.log(this.state.znwns+'///2222')
    return (
      <View className='page'>
        <View className='qun-bgbanner'>
          <Hearder propItem={list_date} porpNav={this.state.navindex} onHandOpen={this.open.bind(this)}></Hearder>
        </View>
        <ScrollView className='qun-goods' scrollY='true' style={'height:'+this.pageheight+'px'} onScrollToLower={this.loadMore.bind(this,'')}>
          <View className='qun-znwn' style={result.length!=0?'display:none':'display:block'}>{this.state.znwns}</View>
          <View className='qun-hodo'>
            <View className='qun-hodos'>
              {result.map((item, index) => (
                <View className='qun-good'>
                  <View className='qun-pkimg' onClick={this.opendetails.bind(this,'/pages/pkgo/pkgodetails',item.commodityId,item.shopId,item.dealerId,item.freeGoSetting.shopCommodityId,'')}>
                    <View className='qun-pktime'>{item.freeGoSetting.ruleName}{item.freeGoSetting.pkTime}</View>
                    <Image mode='scaleToFill' className='ban-hodoimgs' src={item.logo}></Image>
                  </View>
                  <View className='qun-goodtitle'>
                    <View className='goods-title'>
                      {item.commodityName}
                    </View>
                  </View>
                  <View className='qun-goodtitle'>
                    <Text className='goods-money'>商场价:￥{item.price}</Text>
                    <Text className='goods-original'>原价:￥{item.originalprice}</Text>
                  </View>
                  {item.freeGoOrderList.map((item1, index1) => (
                    <View className='qun-pk'>
                      <View className='pk-left'>
                        <Image className='pk-pic' src={item1.avatar}></Image>
                        <Text className='pk-name'>{item1.nickName}</Text>
                      </View>
                      <View className='pk-left'>
                        <View className='pk-remind'>
                          <View className='remind-num'>
                            还差<Text className='pk-number'>{item1.theNumberOfRemCoUsers}</Text>人
                          </View>
                          <View className='remind-time'>
                            {this.countDowns(this.state.nowDate, item1.expiredCollageTime)}
                          </View>
                        </View>
                        <View className='pk-go' onClick={this.opendetails.bind(this,'/pages/pkgo/pkgodetails',item.commodityId,item.shopId,item.dealerId,item.freeGoSetting.shopCommodityId,item1.id)}>
                          去PK
                        </View>
                      </View>
                    </View>
                  ))}
                </View>
              ))}
            </View>
          </View>
        </ScrollView>
      </View>
    )
  }
}

 